<template>
  <el-dialog
    :visible.sync="visible"
    :title="dataForm.details ? '详情' : !dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="close()"
    @open="open()"
    :destroy-on-close="true"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()"
      :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'"
      label-position="right"
      :disabled="disabled"
    >
      <el-row>
        <el-col :span="24">
          <p class="pdl60">
            <span style="color: red">*</span>车辆图片<span
              >(支持png、jpg，建议尺寸750*420px，最多1张)</span
            >
          </p>
        </el-col>
        <el-col :span="12">
          <el-form-item label="" prop="pic">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :on-remove="(file, fileList) => handleRemove(file, fileList)"
              :on-success="(res, file) => handleAvatarSuccess(res, file)"
              :before-upload="beforeAvatarUpload"
              :show-file-list="false"
              :limit="5"
            >
              <img v-if="dataForm.pic" :src="dataForm.pic" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="车辆名称" prop="name">
            <el-input
              type="text"
              v-model="dataForm.name"
              :placeholder="disabled ? '' : '车辆名称'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属公司" prop="rentalcarCompanyId">
            <SelectComponent
              dictType=""
              v-model="dataForm.rentalcarCompanyId"
              :options="companyOptions"
              :placeholder="disabled ? '' : '所属公司'"
              ref="company_sc"
            >
            </SelectComponent>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="电瓶功率" prop="electromobilePower">
            <el-input
              type="text"
              v-model="dataForm.electromobilePower"
              :placeholder="disabled ? '' : '电瓶功率'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="续航(KM)" prop="endurance">
            <el-input
              type="number"
              v-model="dataForm.endurance"
              :placeholder="disabled ? '' : '续航(KM)'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="每日租金(元)" prop="price">
            <el-input
              type="number"
              v-model="dataForm.price"
              :placeholder="disabled ? '' : '每日租金(元)'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="押金" prop="depositType">
            <SelectComponent
              dictType=""
              v-model="dataForm.depositType"
              :options="yjOptions"
              :placeholder="disabled ? '' : '押金'"
              ref="depositType_sc"
            >
            </SelectComponent>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否投保">
            <el-switch
              v-model="isInsureType"
              active-text="是"
              inactive-text="否"
            ></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer" v-if="!disabled">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
    <!-- 裁剪框 -->
    <cropper-dlg
      v-if="showCropper"
      :dialogVisible.sync="showCropper"
      :img-file="currentFile"
      ref="vueCropper"
      @upload="cropperUpload"
    ></cropper-dlg>
  </el-dialog>
</template>
  
  <script>
import Cookies from "js-cookie";
import debounce from "lodash/debounce";
import mixinRegionModule from "@/mixins/region-module";

export default {
  mixins: [mixinRegionModule],

  data() {
    return {
      currentFile: "",
      cropperIndex: null,
      showCropper: false, //裁剪弹框
      isCropper: true, //上传之前是否显示裁剪
      visible: false,
      url: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      fileList: [],
      companyOptions: [],
      yjOptions: [
        { dictValue: 0, dictLabel: "芝麻免押金" },
        { dictValue: 1, dictLabel: "500" },
        { dictValue: 2, dictLabel: "1000" },
        { dictValue: 3, dictLabel: "1500" },
        { dictValue: 4, dictLabel: "2000" },
      ],
      isInsureType: true,
      dataForm: {
        id: "",
        pic: "",
        name: "",
        rentalcarCompanyId: "",
        electromobilePower: "",
        endurance: "",
        price: "",
        depositType: "",
      },
    };
  },
  props: { disabled: Boolean },
  computed: {
    dataRule() {
      return {
        pic: [{ required: true, message: "请上传图片", trigger: "blur" }],

        name: [{ required: true, message: "请输入车辆名称", trigger: "blur" }],
        rentalcarCompanyId: [
          { required: true, message: "请选择所属公司", trigger: "change" },
        ],
        electromobilePower: [
          { required: true, message: "请输入电瓶功率", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入每日租金", trigger: "blur" }],
        depositType: [
          { required: true, message: "请选择押金", trigger: "blur" },
        ],
      };
    },
  },
  methods: {
    open() {
      //获取公司
      this.$http
        .get("/travel/travel/rentalcarcompany/page", {
          params: {
            page: 1,
            limit: 99999,
          },
        })
        .then(({ data: res }) => {
          res.data.list.forEach((l) => {
            this.companyOptions.push({
              dictValue: l.id,
              dictLabel: l.corporateName,
            });
          });
        })
        .catch(() => {});
    },
    handleRemove(file) {
      this.dataForm.pic = "";
    },
    handleAvatarSuccess(res, file) {
      if (res.code === 0) {
        this.dataForm.pic = res.data.url;
      }
    },
    beforeAvatarUpload(file) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error(this.$t("upload.tip", { format: "jpg、png、gif" }));
        return false;
      }
      if (this.isCropper) {
        //显示裁剪
        this.currentFile = file;
        this.cropperIndex = name;
        this.showCropper = true;
        this.$nextTick(() => {
          this.$refs.vueCropper.init();
        });
        return false;
      }
    },
    cropperUpload(data) {
      this.showCropper = false;
      if (data != "close") {
        //裁剪成功后获取的图片
        this.$http.post("/oss/file/aliyunUpload", data).then((res) => {
          if (res.data.code == 0) {
            this.handleAvatarSuccess(res.data);
          }
        });
      }
    },
    close() {
      this.fileList = [];
      this.companyOptions = [];
      this.isInsureType = true;
      this.dataForm = {
        id: "",
        pic: "",
        name: "",
        rentalcarCompanyId: "",
        electromobilePower: "",
        endurance: "",
        price: "",
        depositType: "",
      };
      this.$emit("changeDisabled");
    },

    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.getInfo();
        }
      });
    },
    // 获取信息
    getInfo() {
      this.$http
        .get("/travel/travel/rentalcarelectromobile/" + this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          this.$refs.company_sc.selectValue =
            this.dataForm.rentalcarCompanyId + "";
          this.$refs.depositType_sc.selectValue = this.dataForm.depositType;
          this.isInsureType = this.dataForm.insureType == 0 ? true : false;
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }

          this.dataForm.insureType = this.isInsureType ? 0 : 1;
          if (!this.dataForm.pic) return this.$message.error("请上传车辆图片");
          this.$http[!this.dataForm.id ? "post" : "put"](
            !this.dataForm.id
              ? "/travel/travel/rentalcarelectromobile"
              : "/travel/travel/rentalcarelectromobile",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>
  <style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
  